package cn.iocoder.yudao.module.infra.service.codegen;

import cn.iocoder.yudao.module.infra.dal.dataobject.codegen.DynamicComponent;
import cn.iocoder.yudao.module.infra.dal.mysql.codegen.DynamicComponentMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Optional;

@Service
public class DynamicComponentServiceImpl implements DynamicComponentService {
    @Resource
    private DynamicComponentMapper componentMapper;

    @Getter
    @Value("${magic-ui.custom.scriptBefore:}")
    private String scriptBefore;

    @Getter
    @Value("${magic-ui.custom.scriptAfter:}")
    private String scriptAfter;
    @Getter
    @Value("${magic-ui.custom.scriptAfterWithCss:}")
    private String scriptAfterWithCss;

    @Override
    @Cacheable(value = "selectJsByName")
    public String selectJsByName(String name) {
        DynamicComponent cmp = getDynamicComponent(name);
        if (cmp == null) {
            return StringUtils.EMPTY;
        }
        String compileJs = cmp.getCompileJs();
        if (StringUtils.isBlank(compileJs)) {
            return StringUtils.EMPTY;
        }
        String codeBefore = scriptBefore.replace("{{functionName}}", cmp.getName());
        String codeAfter = scriptAfter;
        if (!StringUtils.isBlank(cmp.getCompileCss())) {
            codeAfter = StringUtils.replace(scriptAfterWithCss, "{{cssContent}}", cmp.getCompileCss());
            codeAfter = StringUtils.replace(codeAfter, "{{time}}", System.currentTimeMillis() + "");
        }
        return codeBefore + compileJs + codeAfter;
    }

    private DynamicComponent getDynamicComponent(String name) {
        QueryWrapper<DynamicComponent> wrapper = new QueryWrapper<>();
        wrapper.eq("name", name); // 指定字段名和值
        wrapper.eq("is_del", 0); // 指定字段名和值
        return componentMapper.selectOne(wrapper);
    }

    @Override
    @Cacheable(value = "selectCssByName")
    public String selectCssByName(String name) {
        DynamicComponent cmp = getDynamicComponent(name);
        return Optional.ofNullable(cmp).map(DynamicComponent::getCompileCss).orElse(StringUtils.EMPTY);
    }
}
